var pmt_invcoldefs = [ {
	key : "invoiceNumber",
	label : "Invoice #",
	formatter: "hlinkFormatter"
}, {
	key : "select",
	label : "Select",
	formatter : "checkbox"
}, {
	key : "invoiceSubmittedDate",
	label : "Invoice Date",
	formatter : "date"
}, {
	key : "totalInvoiceAmount",
	label : "Invoice Amount"
}, {
	key : "remitToSupplierCompany",
	label : "Remit To"
} ];

var pmtinv_lineyuitable = null;
var totalpmtamt = 0;
function inv_populatePayLineItems() {

	if (inv_recdcache != null) {
		var invlDataSource = new YAHOO.util.DataSource();
		invlDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		pmtinv_lineyuitable = new YAHOO.widget.DataTable(
				"pymt_lineDetails_yuiTable", pmt_invcoldefs, invlDataSource, {});
		pmtinv_lineyuitable.addRows(inv_recdcache);
		pmtinv_lineyuitable.unsubscribeAll("checkboxClickEvent");
		pmtinv_lineyuitable.subscribe("checkboxClickEvent", function(oArgs) {
			var elCheckbox = oArgs.target;
			var newValue = elCheckbox.checked;
			var record = this.getRecord(elCheckbox);
			var column = this.getColumn(elCheckbox);
			record.setData(column.key, newValue);
			// Total Invoice Amount:
				var total = 0;
				var rst = pmtinv_lineyuitable.getRecordSet();
				for ( var k = 0; k < rst.getLength(); k++) {
					var data = rst.getRecord(k);
					if (data.getData('select')) {
						total = total
								+ Number(data.getData('totalInvoiceAmount'));
					}
				}

				totalpmtamt = total;
				pymt_selpmtmethod();
			});
	}  else{
		$("pymt_lineDetails_yuiTable").innerHTML = "No Received Invoices"
	}
}

function open_create_payment() {
	u_hideAllSections();
	u_safeShowElement('paymentdetails_table_container');
	init_pmt_create();
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_create_payment()";
	navigationStateArray.push(functionPointerObj);
	}

}
var pmt_date_cal = null;
var pmt_chk_date_cal = null;
function init_pmt_create() {
	totalpmtamt = 0;
	dwr.util.setValue('pymt_date', format_date(new Date()));
	document.getElementById('pymt_notmethod_details').style.display = '';
	document.getElementById('pymt_check_details').style.display = 'none';
	document.getElementById('pymt_eft_details').style.display = 'none';
	document.getElementById('pymt_other_details').style.display = 'none';
	assignAttachmentComponent("attachmentComponetPlaceHolder4");
	assignCommentsComponent("commentComponetPlaceHolder4");
	var emptyopt = [ {
		companyId : null,
		companyName : "   "
	} ];
	if (supp_cache != null && supp_cache.length > 0) {
		dwr.util.removeAllOptions("pymt_supplier");
		dwr.util.addOptions("pymt_supplier", emptyopt, "companyId",
				"companyName");
		dwr.util.addOptions("pymt_supplier", supp_cache, "companyId",
				"companyName");
	} else {
		getPOPreferredSuplierList(usr_comp_cache.companyId);
		setTimeout(init_pmt_create, 2000);
	}

	inv_populatePayLineItems();
	
	if(pmt_date_cal == null){
		pmt_date_cal = new JsDatePick({
			useMode:2,
			target:"pymt_date",
			dateFormat:"%m/%d/%Y",
			limitToToday:true,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
	
	if(pmt_chk_date_cal == null){
		pmt_chk_date_cal = new JsDatePick({
			useMode:2,
			target:"pymt_checkdate",
			dateFormat:"%m/%d/%Y",
			limitToToday:false,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
}

function pymt_selsupplier() {
	var selsupp = dwr.util.getValue('pymt_supplier');
	if (!isEmptyString(selsupp)) {
		for ( var i = 0; i < supp_cache.length; i++) {
			if (supp_cache[i].companyId == selsupp) {
				var opts = [ "  " ];
				dwr.util.removeAllOptions('pymy_supplocation');
				if (supp_cache[i].locations != null
						&& supp_cache[i].locations.length > 0) {
					for ( var k = 0; k < supp_cache[i].locations.length; k++) {
						var str = supp_cache[i].locations[k].addressLine1 + " "
								+ supp_cache[i].locations[k].addressLine2 + " "
								+ supp_cache[i].locations[k].city + " "
								+ supp_cache[i].locations[k].state + " "
								+ supp_cache[i].locations[k].zip;
						opts.push(str);
						str = null;
					}
				}
				dwr.util.addOptions('pymy_supplocation', opts);
			}
		}
	}
}

function pymt_selpmtmethod() {
	var selmethod = dwr.util.getValue('pymt_method_rdo');
	if (selmethod) {
		dwr.util.setValue('sel_pymt_method', selmethod);
		document.getElementById('pymt_notmethod_details').style.display = 'none';
		document.getElementById('pymt_check_details').style.display = 'none';
		document.getElementById('pymt_eft_details').style.display = 'none';
		document.getElementById('pymt_other_details').style.display = 'none';

		if (selmethod.toUpperCase() == "CHECK") {
			document.getElementById('pymt_check_details').style.display = '';
			dwr.util.setValue('pymt_checkamt', totalpmtamt);
		} else if (selmethod.toUpperCase() == "EFT") {
			document.getElementById('pymt_eft_details').style.display = '';
			dwr.util.setValue('pymt_eftamt', totalpmtamt);
		} else if (selmethod.toUpperCase() == "OTHER") {
			document.getElementById('pymt_other_details').style.display = '';
		} else {
			document.getElementById('pymt_notmethod_details').style.display = '';
		}
	} else {
		document.getElementById('pymt_notmethod_details').style.display = '';
	}

}


function updatepymt(){
	var selsupp = dwr.util.getValue('pymt_supplier');
	var selsuppname = "";
	if (isEmptyString(selsupp)) {
		alert('Please select a supplier to make a payment.');
		return;
	}else{
		if (!isEmptyString(selsupp)) {
			for ( var i = 0; i < supp_cache.length; i++) {
				if (supp_cache[i].companyId == selsupp) {
					selsuppname = supp_cache[i].companyName;
				}
			}
		}
	}
	
	var selmethod = dwr.util.getValue('pymt_method_rdo');
	if (isEmptyString(selmethod)) {
		alert('Please select a method of Payment and fill in the payment details.');
		return;
	}
	
	selmethod = selmethod.toUpperCase();
	
	
	
	var inv = {};
	var invli = new Array();
	
	if(pmtinv_lineyuitable != null && pmtinv_lineyuitable.getRecordSet() != null && pmtinv_lineyuitable.getRecordSet().getLength() > 0){
		//browse through the yui table.
		var rset = pmtinv_lineyuitable.getRecordSet();
		for(var i=0;i<rset.getLength();i++){
			var rec = rset.getRecord(i);
			if(rec.getData('select')){
				var invlineitem = rec._oData;
				invli.push(invlineitem.invoiceNumber);
			}
		}
	}
	
	inv.invoices = invli;	
	inv.paymentRecipientMainCompany = selsupp;
	inv.paymentRecipientRemitToCompany = selsupp;
	inv.paymentDate = new Date();
	inv.paymentCreateDate = new Date();
	inv.paymentSubmittedDate = new Date();
	inv.paymentComposer = usrname;
	inv.paymentOwener = usrname;
	inv.totalPaymentAmount = totalpmtamt;
	inv.originatingSystem = 'ATSCOII';
	inv.paymentOriginatorCompany = usr_comp_cache.companyId;
	inv.paymentFromCompanyName = usr_comp_cache.companyName;
	inv.paymentToCompanyName = selsuppname;
	
	//Capture MOP details.
	if(selmethod == "CHECK"){
		inv.checkNumber = dwr.util.getValue('pymt_checknum');
		inv.checkAmount = dwr.util.getValue('pymt_checkamt');
		inv.checkDate = new Date(dwr.util.getValue('pymt_checkdate'));
		inv.checkBankName = dwr.util.getValue('pymt_checkbank');
		inv.methodOfPayment = "CHECK";
	}else if(selmethod == "EFT"){
		inv.eftBankName = dwr.util.getValue('pymt_eftbank');
		inv.eftAccountNumber = dwr.util.getValue('pymt_eftacctnum');
		inv.eftRoutingNumber = dwr.util.getValue('pymt_eftroutingnum');
		inv.eftAmount = dwr.util.getValue('pymt_eftamt');
		inv.methodOfPayment = "EFT";
	}else {
		inv.methodOfPayment = "OTHER";
	}
	
	try{
		var poAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		if(poAtchArr.length > 0){
			inv.paymentAttachmentIds = poAtchArr;
		}
		
		
		var pocmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					pocmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		if(pocmtarr.length > 0){
			inv.paymentComments = pocmtarr;
		}
	}catch(ex){
		
	}
	
	//validate
	
	//Submit the invoice.
	var dwrCallMetaData = {
			callback : success_subpayment,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.postPayment(inv, dwrCallMetaData);
}


function success_subpayment(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		alert("Payment Posted Successfully.");
		return;
	}

	alert("Payment could not be posted. Please try again.");
}